package com.iflytek.jzcpx.procuracy.ocr.component.job;

import java.util.List;

import com.google.common.base.Joiner;
import com.iflytek.jzcpx.procuracy.ocr.component.mq.MessageProducer;
import com.iflytek.jzcpx.procuracy.ocr.service.OcrTaskService;
import com.iflytek.jzcpx.procuracy.ocr.service.RecognizeTaskService;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 批量识别任务结果推送任务
 *
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019-08-13 17:23
 */
@Component
public class TaskResultPushJob {
    private static final Logger logger = LoggerFactory.getLogger(TaskResultPushJob.class);

    @Autowired
    private OcrTaskService ocrTaskService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RecognizeTaskService recognizeTaskService;

    @Autowired
    private MessageProducer messageProducer;

    /**
     * 查询 ocrTask, 获取需要推送的 task 数据
     */
    @Scheduled(fixedDelay = 1000)
    public void pushOcrTaskResult() {
        RLock lock = redissonClient.getLock("pushOcrTaskResult");
        if (lock.tryLock()) {
            try {
                logger.debug("查询已完成的OCR识别任务");
                List<Long> pushableTaskId = ocrTaskService.findPushableTaskId();
                if (CollectionUtils.isEmpty(pushableTaskId)) {
                    return;
                }

                logger.info("批量发送 ocr 结果推送消息. taskIds: {}", Joiner.on(", ").join(pushableTaskId));
                messageProducer.sendOcrResultPushMessage(pushableTaskId);
            }
            catch (Throwable e) {
                logger.warn("已完成的OCR识别任务消息推送异常", e);
            }
            finally {
                lock.unlock();
            }
        }
    }

    /**
     * 图像识别批量任务结果推送
     */
    @Scheduled(fixedDelay = 1000)
    public void pushRecognizeTaskResult() {
        RLock lock = redissonClient.getLock("pushRecognizeTaskResult");
        if (lock.tryLock()) {
            try {
                logger.debug("查询已完成的图像识别任务");
                List<Long> pushableRecognizeTaskIds = recognizeTaskService.findPushableRecognizeTaskId();
                if (CollectionUtils.isEmpty(pushableRecognizeTaskIds)) {
                    return;
                }

                logger.info("批量发送图像识别结果推送消息. recognizeTaskIds: {}", Joiner.on(", ").join(pushableRecognizeTaskIds));
                messageProducer.sendRecognizeResultPushMessage(pushableRecognizeTaskIds);
            }
            catch (Throwable e) {
                logger.warn("已完成的图像识别任务消息推送异常", e);
            }
            finally {
                lock.unlock();
            }
        }
    }

}

